package com.chj.producer_balance.producerconfirm;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 生产者——发送方确认模式--异步监听确认
 */
public class ProducerConfirmAsync {
    public final static String EXCHANGE_NAME = "producer_async_confirm";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 创建连接连接到RabbitMQ
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.200.169.5");
        factory.setVirtualHost("chj_vhost");
        factory.setUsername("chj");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 指定转发
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // TODO 启用发送者确认模式
        channel.confirmSelect();
        // TODO 添加发送者确认监听器
        channel.addConfirmListener(new ConfirmListener(){
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("send_handleAck:"+deliveryTag+",multiple:"+multiple);
            }
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("send_handleNack:"+deliveryTag+",multiple:"+multiple);
            }
        });
        // TODO 添加失败者通知
        channel.addReturnListener(new ReturnListener() {
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                                     AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println("RabbitMq路由失败:  "+routingKey+"."+message);
            }
        });

        String[] routekeys={"hankin01","hankin02"};
        for(int i=0;i<6;i++) {
            String routekey = routekeys[i%2];
            // 发送的消息
            String message = "Hello World_"+(i+1)+("_"+System.currentTimeMillis());
            channel.basicPublish(EXCHANGE_NAME,routekey,true,MessageProperties.PERSISTENT_BASIC,message.getBytes());
            System.out.println(" Sent Message: [" + routekey +"]:'"+ message + "'");
        }
        // 关闭频道和连接
//        channel.close();
//        connection.close();
    }
}
